<?php


/**
 * 封装alert()
 */
function alertMes($mes, $url = null)
{
    echo "<script>alert('{$mes}')</script>";
    if($url != null){
        echo "<script>window.location='{$url}'</script>";
    }
}

/**
 * 检验登陆
 * @param
 * @return bool
 */
function is_login(){
    if(isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0){
        return $_SESSION['admin_id'];
    }else{
        return false;
    }
}
// 两个日期之间的所有日期
function prDates($start,$end){ 
    $dt_start = strtotime($start);
    $dt_end = strtotime($end);
    while ($dt_start<=$dt_end){
        $data[] = date('Y-m-d',$dt_start);
        $dt_start = strtotime('+1 day',$dt_start);
    }
    return $data;
}

/**
 * 计算相隔天数
 */
 function day($Date_1){
        $Date_2=date("Y-m-d");
        $d = explode(' ',$Date_1);
        $Date_1=$d[0];
        $d1=strtotime($Date_1);
        $d2=strtotime($Date_2);
        $Days=round(($d2-$d1)/3600/24);
        return intval($Days);
 }

/**
 * 管理员操作记录
 * @param $log_url 操作URL
 * @param $log_info 记录信息
 */
function adminLog($log_info){
    $add['log_time'] = time();
    $add['admin_id'] = session('admin_id');
    $add['log_info'] = $log_info;
    $add['log_ip'] = getIP();
    $add['log_url'] = __ACTION__;
    M('admin_log')->add($add);
}

/**
 * 项目操作记录
 * @param $log_url 操作URL
 * @param $log_info 记录信息
 */
function productLog($log_info,$pid){
    $add['log_time'] = time();
    $add['pid'] = $pid;
    $add['admin_id'] = session('admin_id');
    $add['log_info'] = $log_info;
    $add['log_ip'] = getIP();
    $add['log_url'] = __ACTION__;
    M('product_log')->add($add);
}

/**
 * 自动下发任务
 */
function task($data){
    $add['pid'] =$data['pid'];
    $add['name'] =$data['name'];
    $add['type'] =$data['type'];
    $add['priority'] =$data['priority'];
    $add['severity'] =$data['severity'];
    $add['t_stop'] =$data['t_stop'];
    $add['add_time'] =$data['add_time'];
    $add['assigname'] =$data['assigname'];
    $add['assign'] =$data['assign'];
    $add['describe'] =$data['describe'];
    $add['status'] = $data['status'];
    $add['cfrom'] = $data['cfrom'];
    $add['link'] = $data['link'];
    $a = M('task')->add($add);
    return $a;
} 



/**
 * 任务操作记录
 * @param $log_url 操作URL
 * @param $log_info 记录信息
 */
function taskLog($log_info,$tid){
    $user = session('admin');
    $add['log_time'] = time();
    $add['tid'] = $tid;
    $add['admin_id'] = $user['name'];
    $add['log_info'] = $log_info;
    $add['log_ip'] = getIP();
    $add['log_url'] = __ACTION__;
    M('task_log')->add($add);
}

/**
 * 获取相隔时间
 * 
 */
function timediff( $begin_time, $end_time )
        {
            if ( $begin_time < $end_time ) {
                $starttime = $begin_time;
                $endtime = $end_time;
            } else {
                $starttime = $end_time;
                $endtime = $begin_time;
            }
          //  $timediff = $endtime - $starttime;
            $cle = $endtime - $starttime; //得出时间戳差值
            $hour = floor($cle/3600); //得出一共多少小时
            return $hour;
        }

/**
 * 获取用户信息
 * @param unknown $admin_id
 */
function getAdminInfo($admin_id){
    return D('admin')->where("admin_id=$admin_id")->find();
}

/**
 * 解析JSON字符串
 * @param unknown $res
 */
function respose($res){
    exit(json_encode($res));
}

/**
 * 发送系统消息
 * @time  2017/02/24
 * $id 发送给谁
 * $name 名称
 * $describe 信息
 */
function SendMessage($id,$name,$describe)
{
/*     $uid = session('admin_id');
    foreach ($id as $key=>$val){
        if($val==$uid){
            unset($id[$key]);
        }
    } */
        $messag = array(
            'sender' => 2017,
            'message' => $describe,
            'send_time' => time(),
            'title' => $name,
            'type'  => 1,
            'status' => 0
        );
        if(!empty($id)){
            foreach ($id as $key) {
                M('message')->data(array('sender' => 2017,'message' => $describe,'send_time' => time(),'title' => $name,'type'  => 1, 'status' => 0,'addressee'=>$key))->add();
            }
        }
}


/**
 * 面包屑导航  用于后台管理
 * 根据当前的控制器名称 和 action 方法
 */
function navigate_admin()
{
    $navigate = include APP_PATH.'Common/Conf/navigate.php';
    $location = strtolower('Admin/'.CONTROLLER_NAME);
    $arr = array(
        '后台首页'=>'javascript:void();',
        $navigate[$location]['name']=>'javascript:void();',
        $navigate[$location]['action'][ACTION_NAME]=>'javascript:void();',
    );
    return $arr;
}


function getMenuList($act_list){
    //根据角色权限过滤菜单
    $menu_list = getAllMenu();
/*     foreach ($menu_list as $k=>$v){
        foreach ($v['sub_menu'] as $key =>$val){
            var_dump($val);
        }
    }exit; */
    if($act_list != 'all'){
        $right = M('system_menu')->where("id in ($act_list)")->cache(true)->getField('right',true);

        foreach ($right as $val){
            $role_right .= $val.',';
        }
        $role_right = explode(',', $role_right);
        foreach($menu_list as $k=>$mrr){
            foreach ($mrr['sub_menu'] as $j=>$v){
                 foreach($v['san'] as $jj=>$vv){
                     if(!in_array($vv['control'].'Controller@'.$vv['act'], $role_right)){
                        unset($menu_list[$k]['sub_menu'][$j]['san'][$jj]);
                     }
                 }
                if(!in_array($v['control'].'Controller@'.$v['act'], $role_right)){
                    unset($menu_list[$k]['sub_menu'][$j]);//过滤菜单
                } 
            }
        }
    }
    return $menu_list;
}

function getAllMenu(){
    return	array(
        'system' => array('name' => '系统设置', 'icon'=>'cogs', 'sub_menu' => array(
            array('name' => '权限管理', 'act'=>'right_list', 'control'=>'System'),
            array('name' => '流程定义', 'act'=>'definition', 'control'=>'System'), 
            array('name' => '公司列表', 'act'=>'company', 'control'=>'Admin'),
            array('name' => '用户列表', 'act'=>'index', 'control'=>'Admin'),
            array('name' => '角色管理', 'act'=>'role', 'control'=>'Admin'),
            array('name' => '日志管理', 'act'=>'log', 'control'=>'Admin'),
        )),
        'project' => array('name' => '项目管理', 'icon'=>'suitcase', 'sub_menu' => array(
            array('name' => '项目列表', 'act'=>'index', 'control'=>'Project'),
            array('name' => '任务状态', 'act'=>'mtask', 'control'=>'Project'),
        )),
        
        'bim' => array('name' => 'BIM管理', 'icon'=>'bold', 'sub_menu' => array(
            array('name' => '基础文件', 'act'=>'basics', 'control'=>'Bim'),
            array('name' => '报告文件', 'act'=>'tation', 'control'=>'Bim','san' =>array(
                array('name' => '碰撞报告', 'act'=>'collisionList', 'control'=>'Bim'),
                /*   array('name' => '节点详图', 'act'=>'collision', 'control'=>'Bim'),
                 array('name' => '管线综合', 'act'=>'drawing', 'control'=>'Bim'), */
            )),
        )),
        
        'family' => array('name' => '族库管理', 'icon'=>'suitcase', 'sub_menu' => array(
           /*  array('name' => '族库系统', 'act'=>'zu', 'control'=>'Family'), */
                array('name' => '族库列表', 'act'=>'library', 'control'=>'Family'),
         /*        array('name' => '添加产品', 'act'=>'libraryadd', 'control'=>'Family'),
                array('name' => '详情', 'act'=>'librarydetail', 'control'=>'Family'),
                array('name' => '审核', 'act'=>'libraryreview', 'control'=>'Family'), */
                array('name' => '品牌', 'act'=>'brand', 'control'=>'Family'), 
        )),
        
        /*  'plan' => array('name' => '测试', 'icon'=>'book', 'sub_menu' => array(
            array('name' => '图表', 'act'=>'dataStatis', 'control'=>'Index'),
        )),  */
        /*   'quality' => array('name' => '质量管理', 'icon'=>'pencil', 'sub_menu' => array(
            array('name' => '工程巡检管理', 'act'=>'#', 'control'=>'#'),
        )),
        'cost' => array('name' => '成本管理', 'icon'=>'group', 'sub_menu' => array(
            array('name' => '成本管理1', 'act'=>'#', 'control'=>'#'),
        )), */
    );
}

// 递归删除文件夹
function delFile($dir,$file_type='') {
    if(is_dir($dir)){
        $files = scandir($dir);
        //打开目录 //列出目录中的所有文件并去掉 . 和 ..
        foreach($files as $filename){
            if($filename!='.' && $filename!='..'){
                if(!is_dir($dir.'/'.$filename)){
                    if(empty($file_type)){
                        unlink($dir.'/'.$filename);
                    }else{
                        if(is_array($file_type)){
                            //正则匹配指定文件
                            if(preg_match($file_type[0],$filename)){
                                unlink($dir.'/'.$filename);
                            }
                        }else{
                            //指定包含某些字符串的文件
                            if(false!=stristr($filename,$file_type)){
                                unlink($dir.'/'.$filename);
                            }
                        }
                    }
                }else{
                    delFile($dir.'/'.$filename);
                    rmdir($dir.'/'.$filename);
                }
            }
        }
    }else{
        if(file_exists($dir)) unlink($dir);
    }
}

/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key,$data = array()){
    $param = explode('.', $config_key);
    if(empty($data)){
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0],'',TEMP_PATH);//直接获取缓存文件
        if(empty($config)){
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type='$param[0]'")->select();
            if($res){
                foreach($res as $k=>$val){
                    $config[$val['name']] = $val['value'];
                }
                F($param[0],$config,TEMP_PATH);
            }
        }
        if(count($param)>1){
            return $config[$param[1]];
        }else{
            return $config;
        }
    }else{
        //更新缓存
        $result =  D('config')->where("inc_type='$param[0]'")->select();
        if($result){
            foreach($result as $val){
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k=>$v){
                $newArr = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
                if(!isset($temp[$k])){
                    M('config')->add($newArr);//新key数据插入数据库
                }else{
                    if($v!=$temp[$k])
                        M('config')->where("name='$k'")->save($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type='$param[0]'")->select();
            foreach ($newRes as $rs){
                $newData[$rs['name']] = $rs['value'];
            }
        }else{
            foreach($data as $k=>$v){
                $newArr[] = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
            }
            M('config')->addAll($newArr);
            $newData = $data;
        }
        return F($param[0],$newData,TEMP_PATH);
    }
}


function encrypt($str){
	return md5(C("AUTH_CODE").$str);
}
            
 
 // 定义一个函数getIP() 客户端IP，
function getIP(){            
    if (getenv("HTTP_CLIENT_IP"))
         $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
         $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    return $ip;
}
// 服务器端IP
 function serverIP(){   
  return gethostbyname($_SERVER["SERVER_NAME"]);   
 }  
 
 

/**
 * 获取随机字符串
 * @param int $randLength  长度
 * @param int $addtime  是否加入当前时间戳
 * @param int $includenumber   是否包含数字
 * @return string
 */
function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
    if ($includenumber){
        $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    }else {
        $chars='abcdefghijklmnopqrstuvwxyz';
    }
    $len=strlen($chars);
    $randStr='';
    for ($i=0;$i<$randLength;$i++){
        $randStr.=$chars[rand(0,$len-1)];
    }
    $tokenvalue=$randStr;
    if ($addtime){
        $tokenvalue=$randStr.time();
    }
    return $tokenvalue;
}

/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
	//return array($http_code, $response,$requestinfo);
}

/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile){
    if(preg_match('/1[34578]\d{9}$/',$mobile))
        return true;
    return false;
}

/**
 * 检查邮箱地址格式
 * @param $email 邮箱地址
 */
function check_email($email){
    if(filter_var($email,FILTER_VALIDATE_EMAIL))
        return true;
    return false;
}



/**
 * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
 * @return boolean
 */
/**
　　* 是否移动端访问访问
　　*
　　* @return bool
　　*/
function isMobile()
{
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    return true;

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
    // 找不到为flase,否则为true
    return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            return true;
    }
        // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
    // 如果只支持wml并且不支持html那一定是移动设备
    // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
            return false;
 } 
